package com.eshop.utils;

import java.util.Collection;
import org.springframework.util.CollectionUtils;
import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.core.RedisTemplate;

public class RedisUtil
{
    private static RedisTemplate<String, Object> redisTemplate;
    
    public static boolean expire(final String key, final long time) {
        try {
            if (time > 0L) {
                RedisUtil.redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public static long getExpire(final String key) {
        return RedisUtil.redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }
    
    public static boolean hasKey(final String key) {
        try {
            return RedisUtil.redisTemplate.hasKey(key);
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public static void del(final String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                RedisUtil.redisTemplate.delete(key[0]);
            }
            else {
                RedisUtil.redisTemplate.delete((Collection)CollectionUtils.arrayToList(key));
            }
        }
    }
    
    public static <T> T get(final String key) {
        return (T)((key == null) ? null : RedisUtil.redisTemplate.opsForValue().get(key));
    }
    
    public static boolean set(final String key, final Object value) {
        try {
            RedisUtil.redisTemplate.opsForValue().set(key, value);
            return true;
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public static boolean set(final String key, final Object value, final long time) {
        try {
            if (time > 0L) {
                RedisUtil.redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            }
            else {
                set(key, value);
            }
            return true;
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    public static long incr(final String key, final long delta) {
        if (delta < 0L) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return RedisUtil.redisTemplate.opsForValue().increment(key, delta);
    }
    
    public static long decr(final String key, final long delta) {
        if (delta < 0L) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return RedisUtil.redisTemplate.opsForValue().increment(key, -delta);
    }
    
    static {
        RedisUtil.redisTemplate = (RedisTemplate<String, Object>)SpringContextUtils.getBean("redisTemplate", RedisTemplate.class);
    }
}
